package net.hn.hnms.biz.plan.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.dynamic.datasource.toolkit.DynamicDataSourceContextHolder;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import net.hn.hnms.biz.plan.domain.DimMiningFace;
import net.hn.hnms.biz.plan.domain.PlanMining;
import net.hn.hnms.biz.plan.mapper.DimMiningFaceMapper;
import net.hn.hnms.biz.plan.mapper.PlanMiningMapper;
import net.hn.hnms.biz.plan.request.PlanMiningReq;
import net.hn.hnms.biz.plan.service.IPlanMiningService;
import net.hn.hnms.biz.plan.vo.PlanMiningVO;
import net.hn.hnms.sys.common.core.constant.Constants;
import net.hn.hnms.sys.common.core.domain.ResponsePage;
import net.hn.hnms.sys.common.core.exception.HuaNengException;
import net.hn.hnms.sys.common.mybatis.core.page.PageQuery;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author zhaoyang
 * 回采计划管理服务层实现
 * @date 2022-08-03
 */

@Service
@DS("master")
public class PlanMiningServiceImpl extends BaseService<PlanMining, PlanMiningVO> implements IPlanMiningService {

    private PlanMiningMapper planMiningMapper;

    private DimMiningFaceMapper dimMiningFaceMapper;

    public PlanMiningServiceImpl(PlanMiningMapper planMiningMapper, DimMiningFaceMapper dimMiningFaceMapper) {
        this.planMiningMapper = planMiningMapper;
        this.dimMiningFaceMapper = dimMiningFaceMapper;
    }

    /**
     *
     * @param planMining
     * @param pageQuery
     *
     * 查询回采计划列表
     */
    @Override
    public ResponsePage<PlanMiningVO> selectPageList(PlanMiningReq planMining, PageQuery pageQuery) {

        Page<PlanMining> page = planMiningMapper.selectPage(pageQuery.build(), buildQuery(planMining).orderByDesc(PlanMining::getMiningPlanCode).orderByDesc(PlanMining::getCreateTime));
        List<PlanMiningVO> list = page.getRecords().stream().map(o -> convert(o, PlanMiningVO.class, o.getMiningPlanType())).collect(Collectors.toList());
        if (CollUtil.isNotEmpty(list)) {
            DynamicDataSourceContextHolder.push("slave");
            List<DimMiningFace> faces = dimMiningFaceMapper.selectList(new LambdaQueryWrapper<DimMiningFace>().eq(StrUtil.isNotBlank(planMining.getMineCode()), DimMiningFace::getMineCode, planMining.getMineCode()));
            Map<String, String> faceMap = faces
                    .stream().collect(Collectors.toMap(DimMiningFace::getMiningFaceId, DimMiningFace::getMiningFaceName));
            DynamicDataSourceContextHolder.clear();
            for (PlanMiningVO planMiningVO : list) {
                planMiningVO.setMiningFaceName(faceMap.get(planMiningVO.getMiningFaceId()));
            }
        }
        return new ResponsePage<>(list, page.getTotal());
    }


    /**
     * 构造查询条件
     * @param req
     * @return LambdaQueryWrapper<PlanDevelopment> 查询条件
     */
    private LambdaQueryWrapper<PlanMining> buildQuery(PlanMiningReq req){
        LambdaQueryWrapper<PlanMining> lqw = new LambdaQueryWrapper<PlanMining>()
                .like(StrUtil.isNotBlank(req.getMiningPlanCode()), PlanMining::getMiningPlanCode, req.getMiningPlanCode())
                .like(StrUtil.isNotBlank(req.getMiningPlanName()), PlanMining::getMiningPlanName, req.getMiningPlanName())
                .eq(StrUtil.isNotBlank(req.getMiningPlanType()), PlanMining::getMiningPlanType, req.getMiningPlanType())
                .eq(StrUtil.isNotBlank(req.getMiningFaceId()), PlanMining::getMiningFaceId, req.getMiningFaceId())
                .eq(StrUtil.isNotBlank(req.getStatus()), PlanMining::getStatus, req.getStatus())
                .and(o->o.eq(req.getMineCode()!=null, PlanMining::getMineCode, req.getMineCode()).or().eq(req.getCompanyCode()!=null, PlanMining::getCompanyCode, req.getCompanyCode()));

        return lqw;
    }

    /**
     *
     * @param planMining
     * 查询掘进计划列表
     */
    @Override
    public List<PlanMiningVO> selectList(PlanMiningReq planMining) {
        List<PlanMining> list = planMiningMapper.selectList(buildQuery(planMining));
        return list.stream().map(o -> convert(o, PlanMiningVO.class, o.getMiningPlanType())).collect(Collectors.toList());
    }

    /**
     *
     * @param planMining
     * 新增回采计划
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int insert(PlanMiningReq planMining) {

        PlanMining insertObj = new PlanMining();
        copyProperties(planMining, insertObj, planMining.getMiningPlanType());
        //自动生成 计划名称 计划编号
        if(planMining.getMiningPlanType().equals("3")){
            insertObj.setMiningPlanName(generatePlanName(planMining.getMiningPlanType(),insertObj.getWeekTimeStart()));
            insertObj.setMiningPlanCode(generatePlanCode(planMining.getMiningPlanType(),insertObj.getWeekTimeStart()));
            insertObj.setPlanStartDate(insertObj.getWeekTimeStart());
            insertObj.setPlanEndDate(insertObj.getWeekTimeEnd());
        }else{
            insertObj.setMiningPlanName(generatePlanName(planMining.getMiningPlanType(),insertObj.getPlanStartDate()));
            insertObj.setMiningPlanCode(generatePlanCode(planMining.getMiningPlanType(),insertObj.getPlanStartDate()));
        }
        insertObj.setStatus("0");
        QueryWrapper<PlanMining> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("mining_plan_code", insertObj.getMiningPlanCode());
        queryWrapper.eq("mining_face_id", insertObj.getMiningFaceId());
        if (planMiningMapper.selectCount(queryWrapper) > 0) {
            throw new HuaNengException(Constants.FAIL, "已存在同一工作面和同一时段的计划");
        }
        return planMiningMapper.insert(insertObj);
    }

    /**
     *
     * @param id
     * 批量删除
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteBatch(List<String> idList) {
        planMiningMapper.deleteBatchIds(idList);
    }

    /**
     *
     * @param planMining
     * 单个修改 按照主键修改信息
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateById(PlanMiningReq planMining) {
        if (StrUtil.isBlank(planMining.getMiningPlanId())) {
            throw new HuaNengException(Constants.FAIL, "id不能为空");
        }
        PlanMining updateObj = new PlanMining();
        copyProperties(planMining, updateObj, planMining.getMiningPlanType());
        updateObj.setMiningPlanName(generatePlanName(planMining.getMiningPlanType(),updateObj.getPlanStartDate()));
        updateObj.setMiningPlanCode(generatePlanCode(planMining.getMiningPlanType(),updateObj.getPlanStartDate()));
        QueryWrapper<PlanMining> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("mining_plan_code", updateObj.getMiningPlanCode());
        queryWrapper.ne("mining_plan_id", updateObj.getMiningPlanId());
        queryWrapper.eq("mining_face_id", updateObj.getMiningFaceId());
        if (planMiningMapper.selectCount(queryWrapper) > 0) {
            throw new HuaNengException(Constants.FAIL, "已存在同一工作面和同一时段的计划");
        }
        int updateCount = planMiningMapper.updateById(updateObj);
        if (updateCount == 0) {
            throw new HuaNengException(Constants.FAIL, "数据不存在");
        }

    }

    /**
     *
     * @param id
     * 按主键id查询详情
     */
    @Override
    public PlanMiningVO selectDetailById(String id) {
        PlanMining planMining = planMiningMapper.selectById(id);
        if (planMining == null) {
            throw new HuaNengException(Constants.FAIL, "数据不存在");
        }
        return convertWithUser(planMining, PlanMiningVO.class);
    }


    /**
     * 启用/禁用
     * @param id 数据id
     * @param status  status: 0:启用 1:禁用
     */
    public void changeStatus(String id, Integer status) {
        if (status == 1 || status == 0) {
            PlanMining planMining = planMiningMapper.selectById(id);
            if (planMining == null) {
                throw new HuaNengException(Constants.FAIL, "数据不存在");
            }
            planMining.setStatus(status + "");
            int res = planMiningMapper.updateById(planMining);
            if (res == 0) {
                throw new HuaNengException(Constants.FAIL, "数据不存在");
            }
            return;
        }
        throw new HuaNengException(Constants.FAIL, "传入的参数错误");
    }
}
